import React, { PropsWithChildren } from 'react';
import { Alert, Form, message } from 'antd';
import {
  ModalForm,
  ProForm,
  ProFormDigit, ProFormSelect,
  ProFormText, ProFormTextArea,
} from '@ant-design/pro-components';
import { carouselV1AdminControllerUpdate, carouselV1AdminControllerCreate } from '@/services/auto/carouselAdmin';
import FileUpload from "@/components/FileUpload";
import {
  carouselMobileJumpType,
  CarouselMobileJumpType,
  CarouselPositionCode,
  carouselPositionCode,
  FileGroup
} from "common/utils/data";
import { useRequest } from "ahooks";

interface FormData extends Omit<API.CarouselAdminCreateDto, 'img'> {
  img: string[];
}

interface Props {
  data?: API.CarouselAdminIndexResult;
  reload?: () => void;
}

export default (props: PropsWithChildren<Props>) => {
  const { data, reload, children } = props;

  const [form] = Form.useForm<FormData>();

  return (
    <ModalForm
      layout="horizontal"
      width={400}
      labelCol={{style: {width: 100}}}
      modalProps={{
        maskClosable: false,
      }}
      form={form}
      onOpenChange={(val) => {
        if (val) {
          if (data?.uuid) {
            form.setFieldsValue({
              ...data,
              img: [data.img],
            });
          }
        } else {
          form.resetFields();
        }
      }}
      title={data?.uuid ? '广告编辑' : '添加广告'}
      trigger={children as JSX.Element}
      onFinish={(values) => {
        let service;
        const newValues: API.CarouselAdminCreateDto = {
          ...values,
          img: values.img[0],
        };
        if (data?.uuid) {
          service = carouselV1AdminControllerUpdate({uuid: data.uuid},newValues);
        } else {
          service = carouselV1AdminControllerCreate(newValues);
        }
        return service
          .then(() => {
            message.success('操作成功');
            reload?.();
            return true;
          })
          .catch(() => {
            return false;
          });
      }}
    >
      <Form.Item name="img" label="图片" rules={[{ required: true, type: 'array', message: '请上传' }]}>
        <FileUpload fileGroup={FileGroup.CAROUSEL} />
      </Form.Item>
      <ProFormText
        name="title"
        label="标题"
        rules={[{ required: true, message: '请输入' }]}
        fieldProps={{
          maxLength: 200,
        }}
      />
      <ProFormText
        name="url"
        label="链接"
        rules={[{ required: true, message: '请输入' }]}
      />
      <ProFormSelect
        name="positionCode"
        label="轮播位"
        options={carouselPositionCode.$listSelect.map(item=>{
          return {
            label: item.label.name,
            value: item.value,
          }
        })}
        rules={[{ required: true, message: '请选择' }]}
        extra={
          <ProForm.Item noStyle shouldUpdate={(prev,cur)=>prev.positionCode !== cur.positionCode}>
            {()=>{
              const positionCode = form.getFieldsValue().positionCode;
              if(!positionCode){
                return <></>
              }
              return carouselPositionCode[positionCode as CarouselPositionCode].desc;
            }}
          </ProForm.Item>
        }
      />
      <ProFormDigit
        name="sort"
        label="排序"
        rules={[{ required: true, message: '请输入' }]}
        fieldProps={{
          min: 1,
          max: 999,
          precision: 0,
        }}
      />
      <ProFormTextArea
        name="desc"
        label="描述"
      />
      <ProFormSelect
        initialValue={CarouselMobileJumpType.NONE}
        name="mobileJumpType"
        label="移动端跳转类型"
        options={carouselMobileJumpType.$listSelect}
      />
      <ProForm.Item noStyle shouldUpdate={(prev,cur)=>{
        return prev.mobileJumpType !== cur.mobileJumpType
      }}>
        {(form)=>{
          const mobileJumpType = form.getFieldValue('mobileJumpType');
          if(mobileJumpType === 'NONE'){
            return <></>
          }
          return <>
            <ProFormText
              name="mobileJumpId"
              label="移动端跳转id"
              rules={[{ required: true, message: '请输入' }]}
              fieldProps={{
                maxLength: 50,
              }}
              extra={
                mobileJumpType === 'BILIBILI' ? <Alert showIcon type="warning" message={<>
                  B站这里须填写avid，请前往
                  <a href="https://bv-av.cn/get-bv-av" target="_blank">工具网站</a>
                  将BV号转换为AV号
                </>} /> : undefined
              }
            />
            <ProFormTextArea
              name="mobileJumpExtra"
              label="移动端跳转扩展参数"
              initialValue="{}"
              rules={[
                {
                  validator: (rule, value, callback)=>{
                    try {
                      JSON.parse(value);
                      callback();
                    }catch (e) {
                      callback('必须是个合法的json')
                    }
                  }
                }
              ]}
            />
          </>
        }}
      </ProForm.Item>
    </ModalForm>
  );
};
